/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include<unordered_map>
using namespace std;
class Solution {
    int _res=0;
    int _targetSum=0;
    //前缀和为0的路径有一个防止当target为根时根统计不上
    unordered_map<long long,short>u_map{{0,1}};
public:
    void __path_sum(TreeNode* root,long long cur){
        if(!root)return ;
        cur+=root->val;
        //1 -2 -4
        if(u_map.find(cur-_targetSum)!=u_map.end()){
            _res+=u_map[cur-_targetSum];
            cout<<root->val<<' '<<cur<<' '<<cur-_targetSum<<endl;
        }
        u_map[cur]++;
        __path_sum(root->left,cur);
        //左边统计完了 删除左边路径前缀和 以免影响右边
        if(root->left)
            u_map[cur+root->left->val]--;
        //统计右边路径
        __path_sum(root->right,cur);
        //删除右边路径前缀和 以免影响其他树
        if(root->right)
            u_map[cur+root->right->val]--;
    }
    int pathSum(TreeNode* root, int targetSum) {
        _targetSum=targetSum;
        __path_sum(root,0);
        return _res;
    }
};